import json
import os.path
import time
import requests
import glob
import numpy as np
import cv2
import config
from matplotlib import pyplot as plt
from hashlib import sha1
import zipfile

def download():
    lb_r = 'label_data'
    sv_dr = 'F:/dl_data/fpv_new_download'
    img_dr = os.path.join(sv_dr, 'image')
    mask_dr = os.path.join(sv_dr, 'mask')
    if not os.path.exists(img_dr):
        os.makedirs(img_dr)
        os.makedirs(mask_dr)

    for pth in glob.glob(os.path.join(lb_r, '*.json')):
        dt = json.loads(open(pth,encoding='utf8').read())
        img_name = dt['image_name']
        image_url = dt['image_url']
        boundarys = dt['object']
        h,w = dt['image_height'],dt['image_width']
        mask = np.zeros(shape=(h,w,len(config.new_label_names)),dtype=np.uint8)



        for b in boundarys:
            label_name = b['labelName']
            pts = []
            tp_mask = np.zeros(shape=(h,w,3),dtype=np.uint8)
            for p in b['boundary']:
                pts.append([int(p['x']), int(p['y'])])
            cv2.fillPoly(tp_mask, [np.asarray(pts)], color=(1, 1,1))
            mask[:,:, config.new_label_dict[label_name]] = tp_mask[:,:,0]
        for i in range(len(config.new_label_names)):
            mask[:,:,i] = mask[:,:,i]*config.label_weight[i]
        lb = np.argmax(mask, axis=2)
        lb = np.asarray(lb, np.uint8)

        plt.imshow(lb)
        plt.show()

        cv2.imwrite(os.path.join(img_dr, img_name.replace('.jpg','.png')), lb)

        with open(os.path.join(img_dr, img_name), 'wb') as f:
            r = requests.get(image_url)
            f.write(r.content)
            f.flush()

def auto_download():
    accessid = 'TM1346a2aP58lEKm08IXmzLL'
    accesskey = 'Ug134V7uHS6ZxgEA71u973kwC02rm9'
    timestamp = str(int(time.time()))
    ak = accessid+accesskey+timestamp
    signature = sha1(ak.encode('utf-8')).hexdigest()
    headers = {"content-type":"application/json"}
    body = {
        'datasetSn':'SJJ-00593',
        'datasetVersion':4,
        'markStatusList':[8],
        'markDownloadMethod':1
    }
    token_url = 'https://ai.xa.com/mark-data/api/datasetDataResult/downloadResult?accessId=' + accessid + '&timestamp=' + timestamp + '&signature=' + signature
    r = requests.post(token_url, json=body, headers=headers)
    with open('data.zip','wb') as f:
        f.write(r.content)

def express():
    zpf = zipfile.ZipFile('data.zip')
    zpf.extractall('./label_data')

if __name__ == '__main__':
    #auto_download()
    #express()
    download()





